import config from './map.conf'
import jsonp from 'jsonp'
class Location_web {
  ready (callback) {
    if (window.BMap) {
      callback()
    } else {
      // 异步加载百度地图实例，需要写上接口回调函数。否则 new MBap 会提示报错
      window.$tool.loadScript(`${config.B_DOMAIN}/api?v=2.0&ak=${config.B_KEY}&callback=mapCallback`, function () {
        window.mapCallback = () => {
          setTimeout(function () {
            callback()
          }, 500)
        }
      })
    }
  }
  /**
   * 百度地图经纬度转换
   * @param points 需要被转换的经纬度
   * @param opts 转换配置请参考(http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition)
   * @returns {Promise<any>}
   */
  static geoconv(points, opts = {}) {
    let url = `${config.B_DOMAIN}/geoconv/v1/?`
    url += `coords=${points.longitude},${points.latitude}`
    url += `&from=${opts.form || points.from || 1}&to=${opts.form || 5}`
    url += `&ak=${config.B_KEY}`
    console.log('geoconv',url)
    return new Promise((resolve, reject) => {
      console.log('geoconv-----1')
      jsonp(url, function (err, ret) {
        // console.log('geoconv-----2',err,ret)
        if (err) {
          console.error(err)
          reject(reject)
        }
        // console.log('geoconv-----3',ret)
        if (ret && ret.status === 0) {
          resolve({
            longitude: ret.result[0].x,
            latitude: ret.result[0].y
          })
        }else{
          reject('web获取位置出错!')
          console.error('web获取位置出错!')
        }
      })
    })
  }
  /**
   * 根据经纬度获取位置信息
   * @param pos
   * @param opts 配置(http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad)
   * @returns {Promise<any>}
   */
  static geocoder(pos, opts = {}) {
    let url = `${config.B_DOMAIN}/geocoder/v2/?callback=renderReverse`
    url += `&coordtype=gcj02`
    url += `&output=json`
    url += `&pois=0`
    url += `&latest_admin=1`
    url += `&location=${pos.latitude},${pos.longitude}`
    url += `&ak=${config.B_KEY}`
    console.log('geocoder',url)
    return new Promise((resolve, reject) => {
      jsonp(url, (err, pos) => {
        // console.log('geocoder-----1',err)
        if (err) {
          console.error(err)
          reject(err)
        }
        // console.log('geocoder-----3',pos)
        resolve(pos)
      })
    })
  }
  static getAddressBMap (callback) {
    const geolocation = new BMap.Geolocation()
    geolocation.enableSDKLocation()
    geolocation.getCurrentPosition(function (ret) {
      if (this.getStatus() === BMAP_STATUS_SUCCESS) {
        // 获取位置详情
        const myGeo = new BMap.Geocoder()
        const mapPoint = new BMap.Point(ret.longitude, ret.latitude)
        myGeo.getLocation(mapPoint, function (result) {
          // console.log(result)
          if (result) {
            // 百度坐标转火星坐标
            const transPoint = gcoord.transform([result.point.lng, result.point.lat], gcoord.BD09, gcoord.GCJ02);
            callback({
              province: result.addressComponents.province,
              city: result.addressComponents.city,
              district: result.addressComponents.district,
              lon: transPoint[0],
              lat: transPoint[1],
              address: result.address
            })
          } else {
            callback({})
          }
        })
      } else {
        callback({})
      }
    })
  }
  getAddress (callback) {
    this.ready(() => {
      getLocation(callback)
    })
  }
}
/*百度定位在浏览器中偏差较大，采用GPS位置转换的方式*/
function getLocation(cb){
  if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition((res) => {
      // GPS坐标转火星坐标
      // const transPoint = gcoord.transform([res.coords.longitude, res.coords.latitude], gcoord.WGS84, gcoord.GCJ02);
      // cb && cb({
      //   lon: transPoint[0],
      //   lat: transPoint[1]
      // })
      // GPS坐标转百度坐标
      showPosition(res, cb)
    }, () => {
      Location_web.getAddressBMap(cb)
      // showError(error)
    })
  }else{
    // alert("浏览器不支持地理定位");
    //百度定位优先调用浏览器原生定位接口进行定位，浏览器定位失败之后尝试进行精确IP定位
    Location_web.getAddressBMap(cb)
  }
}
// 获取用户经纬度
function showPosition(position, cb){
  //GPS经纬度转百度坐标
  const x = position.coords.latitude;
  const y = position.coords.longitude;
  const gpsPoint = new BMap.Point(y, x);
  setTimeout(function(){
    const convertor = new BMap.Convertor();
    const pointArr = [];
    pointArr.push(gpsPoint);
    convertor.translate(pointArr, 1, 5, function (data){
      translateCallback(data, cb)
    })
  }, 1000);
}
// 将GPS经纬度转为百度地图经纬度
function translateCallback(data, cb){
  const point = data.points[0];
  const nowPointLng = data.points[0].lng;
  const nowPointLat = data.points[0].lat;
  const BPoints = new BMap.Point(point.lng, point.lat)
  initBMapAddress(BPoints, cb)
}
// 报错信息
function showError(error){
  switch(error.code) {
    case error.PERMISSION_DENIED:
      alert("定位失败,用户拒绝请求地理定位,请检查权限设置");
      break;
    case error.POSITION_UNAVAILABLE:
      alert("定位失败,位置信息不可用");
      break;
    case error.TIMEOUT:
      alert("定位失败,获取用户位置超时");
      break;
    case error.UNKNOWN_ERROR:
      alert("定位失败,定位系统失效");
      break;
  }
}
function initBMapAddress(Bpoints,cb){
  let address = {}
  // 获取位置详情
  const myGeo = new BMap.Geocoder()
  myGeo.getLocation(Bpoints, function (result) {
    if (result) {
      // 百度坐标转火星坐标
      const transPoint = gcoord.transform([result.point.lng, result.point.lat], gcoord.BD09, gcoord.GCJ02);
      address = {
        lon: transPoint[0],
        lat: transPoint[1],
        province: result.addressComponents.province,
        city: result.addressComponents.city,
        district: result.addressComponents.district,
        address: result.address
      }
    }
    cb && cb(address)
  })
}
export default Location_web
